// 用户信息相关的
const { defineStore } = Pinia;
const {computed} = Vue
export const useUserInfoStore = defineStore("userInfo", {
  state: () => {
    return {
      userInfo: {
        number: 0,
        _id: "",
      },
      token: "",
      localforageJS: null, //
      localforageIMG: null, //
      localforageAPI: null, //
      article_total: 0,
      blog_class_option: {},
      options: {},
      tags: [],
      keyboardEventKay: "",
      navId: "",
      userOptions: [],
      navlist: [],
      platformType: 1, // 在哪一端 1 pc 2 移动 3 平板
      collectionList: [], // 用户收藏列表

    };
  },
  getters: {
    userInfoNumber: (state) => computed(() => state.userInfo.number || 0),
    keyboardEventKayGetter: (state) => computed(() => state.keyboardEventKay),
    userInfoGetter: (state) => computed(() => state.userInfo),
    isLogin: (state) => computed(() => state.userInfo._id),
    isAdmin: (state) => computed(() => state.userInfo.role === "admin"),
    provincial_flow_typeOptions: (state) =>
      computed(() => state.options?.provincial_flow_typeOptions),
    userdata: (state) => computed(() => state?.userInfo || {}),
  },
  actions: {
    async GET_COLLECTIONS_LIST(isReload = false) {
      if (this.isLogin) {
        const res = await apis.get_collection_articles({
          cache: true,
          expire_time: isReload ? -1 : 5 * 60 * 1000,
        });
        if (!isArray(res?.data?.data)) {
          Toast("获取收藏文章失败");
          return;
        }
        this.collectionList = res.data.data;
      }
    },
    SET_platformType(data) {
      this.platformType = data;
    },
    // 直接设置 navlist
    SET_NAV_LIST(row) {
      if (!isArray(row)) {
        Toast("SET_NAV_LIST参数必须是数组");
        return;
      }
      this.navlist = row;
    },

    // 获取全局navlist
    async GET_NAV_LIST({ isReload = false, ...other } = {}) {
      let params = {
        cache: true,
        ...other,
      };
      if (isReload) {
        params.expire_time = -1;
      }
      const res = await apis.get_classs(params);
      if (Array.isArray(res?.data?.list)) {
        this.navlist = res.data.list;
        return true;
      }
      Toast("获取全局navlist失败");
      return false;
    },
    async SET_USER_OPTIONS() {
      const res = await apis.get_authors({
        page: 1,
        limit: 100,
        cache: true,
      });

      if (isArray(res?.data?.data)) {
        this.userOptions = res.data.data.map((item) => {
          return {
            label: item.username,
            value: item._id,
          };
        });
      }
    },
    SET_NAV_ID(data) {
      this.navId = data;
    },
    SET_KEYBORDER_EVENT_KEY(data) {
      this.keyboardEventKay = data;
      setTimeout(() => {
        this.keyboardEventKay = "";
      }, 50);
    },
    setUserInfo(userInfo) {
      const { user, options, token } = userInfo;
      if (isObject(user)) {
        if (Object.keys(user).length === 0) {
          this.userInfo = {};
        } else {
          Object.assign(this.userInfo, user);
        }
      }
      if (typeof token === "string") {
        this.token = token;
      }

      if (isArray(options)) {
        this.options = options;
      }
    },

    // 同步用户基本信息
    async POST_USER_SYNC(isRelaod = false) {
      const { email, password } = this.userInfo;
      // 同步用户信息 最小间隔5min
      if (!email || !password) return;

      if (!isRelaod) {
        let POST_USER_SYNC_store = await getStore(
          "POST_USER_SYNC_store",
          false,
          {
            expire_time: 5 * 60 * 1000,
          }
        );
        if (POST_USER_SYNC_store) return;
      }

      // 同步用户设备信息 每24h 上传一次用户设备信息
      const userSTime = await getStore("userSTime", 0, {
        expire_time: 24 * 3600 * 1000, // 24h
      });
      const currentTime = Date.now();

      setStore("POST_USER_SYNC_lastTime", currentTime);

      let data1 = {
        load_time: [],
        netInfo: [],
      };

      // 每一段时间才会上传一次用户信息到服务器
      if (userSTime === 0 && isBrowser) {
        const performance_begin_time =
          sessionStorage.getItem("performance_begin_time") || 0;
        const performance_mounted_time =
          sessionStorage.getItem("performance_mounted_time") || 0;

        const performance_indexdb_begin_time =
          sessionStorage.getItem("performance_indexdb_begin_time") || 0;

        if (
          performance_begin_time &&
          performance_mounted_time &&
          performance_indexdb_begin_time
        ) {
          data1.load_time = [
            {
              label: "加载到mounted时间",
              value: performance_mounted_time - performance_begin_time,
            },
            {
              label: "加载完异步文件时间",
              value: currentTime - performance_begin_time,
            },
            {
              label: "加载异步文件时间",
              value: currentTime - performance_indexdb_begin_time,
            },
          ];
        }

        // 网络情况
        let {
          downlink = "",
          effectiveType = "",
          rtt = "",
        } = navigator?.connection || {};
        const { appVersion = "" } = navigator || {};
        data1.netInfo = [
          {
            label: "网络速度",
            value: downlink,
          },
          {
            label: "网络类型",
            value: effectiveType,
          },
          {
            label: "网络延迟",
            value: rtt,
          },
          {
            label: "浏览器版本",
            value: appVersion,
          },
          {
            label: "终端",
            value: isPc() ? "PC端" : "移动端",
          },
        ];

        setStore("userSTime", currentTime);
      }

      const res = await apis.post_user_sync({
        email,
        password,
        sync: "sync",
        _autoTip: false,
        type: "2",
        ...data1,
      });
      const { data = {}, iolationsNumber = 0 } = res?.data || {};
      if (data) {
        Object.assign(this.userInfo, {
          ...data,
          iolationsNumber,
        });

        if (isBrowser && isRelaod) {
          // 清除外部跳转过来的携带
          updateUrl("email", null);
          updateUrl("password", null);
          updateUrl("user_id", null);
        }

        setStore("POST_USER_SYNC_store", true);
      }
    },
    SET_LOCALFORAGEJS(data) {
      this.localforageJS = data;
    },
    SET_LOCALFORAGEIMG(data) {
      this.localforageIMG = data;
    },
    SET_LOCALFORAGEAPI(data) {
      this.localforageAPI = data;
    },

    // 拉取基本配置 默认缓存时间
    async SET_OPTIONS(expire_time = 10 * 60 * 1000) {
      try {
        const res = await apis.get_options({
            cache: true,
            expire_time,
          });
        
        const {
          article_total = 0,
          blog_class_option = {},
          data = {},
          tags = [],
        } = res.data.value?.data || {};
        this.article_total = article_total;
        this.blog_class_option = blog_class_option;
        this.options = data;
        this.tags = tags;
      } catch (e) {
        Toast(e);
      }
    },
  },
  // 启用持久化
    persist: {
        // 持久化存储的路径
        key: 'custom-key', // 默认是 store 的 id

        // 存储到 sessionStorage 而不是 localStorage
        // storage: sessionStorage,

        // 指定要持久化的部分状态
        paths: ['userInfo'], // 只有 count 会被持久化
    }
});
